package com.kadron.common;

import java.io.File;
import java.io.Serializable;

import javax.servlet.ServletContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Create;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.contexts.ServletLifecycle;

import com.kadron.dao.KUserDAO;
import com.kadron.service.CommonUserService;

@Startup(depends = "kadronEntityManagerFactory")
@AutoCreate
@Scope(ScopeType.APPLICATION)
@Name("kInitParam")
public class KInitParams implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2279318520328599763L;
	
	public static String WEBAPPS_PATH = "D:/kadron/servers/apache-tomcat-7.0.35/webapps";
	public static String IMG_PATH = "/kimg";
	public static int MAX_IMG_SIZE = 1024000;
	
	public static final String IMG_PREFIX = "/i_";
	public static final String AVATAR_PREFIX = "/av_";
	public static final String SLASH_SEPARATOR = "/";
	
	public static int SILVER_KADRONS = 10;
	public static int GOLD_KADRONS = 100;
	public static int PLATINUM_KADRONS = 200;
	
	public static int SILVER_DISCOUNT = 10;
	public static int GOLD_DISCOUNT = 20;
	public static int PLATINUM_DISCOUNT = 20;
	
	public static int SILVER_DURATION = 365;
	public static int GOLD_DURATION = 365;
	public static int PLATINUM_DURATION = 365;

	@In
	private KUserDAO userDAO;
	
	@Create
	public void init() {
		ServletContext servletContext = ServletLifecycle.getServletContext();
		String webapp_path = servletContext.getInitParameter("WEBAPPS_PATH");
		String img_path = servletContext.getInitParameter("IMG_PATH");
		String max_img_size = servletContext.getInitParameter("MAX_IMG_SIZE");
		if (!KUtil.isEmpty(webapp_path)) {
			WEBAPPS_PATH = (webapp_path);
		}
		if (!KUtil.isEmpty(img_path)) {
			IMG_PATH = (img_path);
		}
		if (!KUtil.isEmpty(max_img_size)) {
			try {
				MAX_IMG_SIZE = (Integer.parseInt(max_img_size));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		File imgdir = new File(KInitParams.WEBAPPS_PATH+KInitParams.IMG_PATH);
		if (!imgdir.exists()) {
			imgdir.mkdir();
		}
		Long maxOrdinal = userDAO.getMaxOrdinal();
		if (maxOrdinal != null && maxOrdinal > 1) {
			CommonUserService.initCounter(maxOrdinal);
		}
	}
	
	public String getImgPath() {
		return KInitParams.IMG_PATH;
	}

}
